//
//  EmitterSnowViewController.m
//  wuliangye
//
//  Created by jarze on 16/2/19.
//  Copyright © 2016年 jarze. All rights reserved.
//
//Properties:
//
//birthRate:粒子产生系数，默认1.0；
//
//emitterCells: 装着CAEmitterCell对象的数组，被用于把粒子投放到layer上；
//
//emitterDepth:决定粒子形状的深度联系：emitter shape
//
//emitterZposition:发射源的z坐标位置；
//
//lifetime:粒子生命周期
//
//preservesDepth:不是多很清楚（粒子是平展在层上）
//
//
//scale:粒子的缩放比例：
//
//seed：用于初始化随机数产生的种子
//
//spin:自旋转速度
//
//velocity：粒子速度
//
//CAEmitterCell
//
//CAEmitterCell类代从从CAEmitterLayer射出的粒子；emitter cell定义了粒子发射的方向。
//
//alphaRange:  一个粒子的颜色alpha能改变的范围；
//
//alphaSpeed:粒子透明度在生命周期内的改变速度；
//
//birthrate：粒子参数的速度乘数因子；每秒发射的粒子数量
//
//blueRange：一个粒子的颜色blue 能改变的范围；
//
//blueSpeed: 粒子blue在生命周期内的改变速度；
//
//color:粒子的颜色
//
//contents：是个CGImageRef的对象,既粒子要展现的图片；
//
//contentsRect：应该画在contents里的子rectangle：
//
//emissionLatitude：发射的z轴方向的角度
//
//emissionLongitude:x-y平面的发射方向
//
//emissionRange；周围发射角度
//
//emitterCells：粒子发射的粒子
//
//enabled：粒子是否被渲染
//
//greenrange: 一个粒子的颜色green 能改变的范围；
//
//greenSpeed: 粒子green在生命周期内的改变速度；
//
//lifetime：生命周期
//
//lifetimeRange：生命周期范围      lifetime= lifetime(+/-) lifetimeRange
//
//magnificationFilter：不是很清楚好像增加自己的大小
//
//minificatonFilter：减小自己的大小
//
//minificationFilterBias：减小大小的因子
//
//name：粒子的名字
//
//redRange：一个粒子的颜色red 能改变的范围；
//
//redSpeed; 粒子red在生命周期内的改变速度；
//
//scale：缩放比例：
//
//scaleRange：缩放比例范围；
//
//scaleSpeed：缩放比例速度：
//
//spin：子旋转角度
//
//spinrange：子旋转角度范围
//
//style：不是很清楚：
//
//velocity：速度
//
//velocityRange：速度范围
//
//xAcceleration:粒子x方向的加速度分量
//
//yAcceleration:粒子y方向的加速度分量
//
//zAcceleration:粒子z方向的加速度分量
#import "EmitterSnowViewController.h"
#define randColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]
@interface EmitterSnowViewController ()
@property (nonatomic, strong) CALayer   *movedMask;

@end

@implementation EmitterSnowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    static int i = 0;
    switch (i++ % 4) {
        case 0:{
            [self setUp];
        }
            break;
        case 1:{
            [self setUp2];
        }
            break;
        case 2:{
            [self setUp1];
        }
            break;
        case 3:{
        }
            break;
        default:
            break;
            
    }
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//星星
- (void)setUp
{
   
    CAEmitterLayer *emitter = [CAEmitterLayer layer];
    emitter.frame = self.view.bounds;
    [self.view.layer addSublayer:emitter];
    
    //configure emitter
    emitter.renderMode = kCAEmitterLayerAdditive;
    emitter.emitterPosition = CGPointMake(emitter.frame.size.width / 2.0, emitter.frame.size.height / 2.0);
    
    //create a particle template
    CAEmitterCell *cell = [[CAEmitterCell alloc] init];
    cell.contents = (__bridge id)[UIImage imageNamed:@"Star"].CGImage;
    cell.birthRate = 50;
    cell.lifetime = 5.0;
//    cell.color = [UIColor colorWithRed:1 green:0.8 blue:0.1 alpha:1.0].CGColor;
    
    // 设置雪花形状的粒子的颜色
    cell.color      = [[UIColor whiteColor] CGColor];
    cell.redRange   = 255.f;
    cell.greenRange = 255.f;
    cell.blueRange  = 255.f;
    
    //旋转
    cell.spin = 1.f;
    cell.spinRange = 1.f;
    
//    cell.alphaSpeed = -0.2;
    
    //速度
    cell.velocity = 100;
    cell.velocityRange = 50;
    
    // 周围发射角度
    cell.emissionRange = M_PI * 2.0;
    
    cell.scale = 0.7;
    cell.scaleSpeed = -0.1;
    

    //add particle template to emitter
    emitter.emitterCells = @[cell];

}

//雪花
- (void)setUp1
{
     self.view.backgroundColor = [UIColor blackColor];
    
    // 创建粒子Layer
    CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
    
    // 粒子发射位置
    snowEmitter.emitterPosition = CGPointMake(120,0);
    
    // 发射源的尺寸大小
    snowEmitter.emitterSize     = self.view.bounds.size;
    
    // 发射模式
    snowEmitter.emitterMode     = kCAEmitterLayerSurface;
    
    // 发射源的形状
    snowEmitter.emitterShape    = kCAEmitterLayerLine;
    
    // 创建雪花类型的粒子
    CAEmitterCell *snowflake    = [CAEmitterCell emitterCell];
    
    // 粒子的名字
    snowflake.name = @"snow";
    
    // 粒子参数的速度乘数因子
    snowflake.birthRate = 20.0;
    //粒子生命周期
    snowflake.lifetime  = 120.0;
    
    // 粒子速度
    snowflake.velocity  = 10.0;
    
    // 粒子的速度范围（调节  velocity +- velocityRange）
    snowflake.velocityRange = 10;
    
    // 粒子y方向的加速度分量
    snowflake.yAcceleration = 2;
    
    // 周围发射角度
    snowflake.emissionRange = 0.5 * M_PI;
    
    // 子旋转角度范围
    snowflake.spinRange = 0.25 * M_PI;
    snowflake.contents  = (id)[[UIImage imageNamed:@"snow"] CGImage];
    
    // 设置雪花形状的粒子的颜色
    snowflake.color      = [[UIColor whiteColor] CGColor];
    snowflake.redRange   = 2.f;
    snowflake.greenRange = 2.f;
    snowflake.blueRange  = 2.f;
    
    snowflake.scaleRange = 0.6f;
    snowflake.scale      = 0.7f;
    
    snowEmitter.shadowOpacity = 1.0;
    snowEmitter.shadowRadius  = 0.0;
    snowEmitter.shadowOffset  = CGSizeMake(0.0, 0.0);
    
    // 粒子边缘的颜色
    snowEmitter.shadowColor  = [[UIColor whiteColor] CGColor];
    
    // 添加粒子
    snowEmitter.emitterCells = @[snowflake];
    
    // 将粒子Layer添加进图层中
    [self.view.layer addSublayer:snowEmitter];
    // 形成遮罩
    UIImage *image      = [UIImage imageNamed:@"alpha"];
    _movedMask          = [CALayer layer];
    _movedMask.frame    = (CGRect){CGPointZero, image.size};
    _movedMask.contents = (__bridge id)(image.CGImage);
    _movedMask.position = self.view.center;
    snowEmitter.mask    = _movedMask;
    
    // 拖拽的View
    UIView *dragView = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, image.size}];
    dragView.center  = self.view.center;
    [self.view addSubview:dragView];
    
    // 给dragView添加拖拽手势
    UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [dragView addGestureRecognizer:recognizer];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    
    // 拖拽
    CGPoint translation    = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
    // 关闭CoreAnimation实时动画绘制(核心)
    [CATransaction setDisableActions:YES];
    _movedMask.position = recognizer.view.center;
}




- (void)setUp2{
    // Configure the particle emitter to the top edge of the screen
    CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
    snowEmitter.emitterPosition = CGPointMake(self.view.bounds.size.width / 2.0, -30);
    snowEmitter.emitterSize		= CGSizeMake(self.view.bounds.size.width * 2.0, 0.0);;
    
    // Spawn points for the flakes are within on the outline of the line
    snowEmitter.emitterMode		= kCAEmitterLayerOutline;
    snowEmitter.emitterShape	= kCAEmitterLayerLine;
    
    // Configure the snowflake emitter cell
    CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
    
    snowflake.birthRate		= 1.0;
    snowflake.lifetime		= 120.0;
    
    snowflake.velocity		= -10;				// falling down slowly
    snowflake.velocityRange = 10;
    snowflake.yAcceleration = 2;
    snowflake.emissionRange = 0.5 * M_PI;		// some variation in angle
    snowflake.spinRange		= 0.25 * M_PI;		// slow spin
    
    snowflake.contents		= (id) [[UIImage imageNamed:@"DazFlake"] CGImage];
    snowflake.color			= [[UIColor colorWithRed:0.600 green:0.658 blue:0.743 alpha:1.000] CGColor];
    
    // Make the flakes seem inset in the background
    snowEmitter.shadowOpacity = 1.0;
    snowEmitter.shadowRadius  = 0.0;
    snowEmitter.shadowOffset  = CGSizeMake(0.0, 1.0);
    snowEmitter.shadowColor   = [[UIColor whiteColor] CGColor];
    
    // Add everything to our backing layer below the UIContol defined in the storyboard
    snowEmitter.emitterCells = [NSArray arrayWithObject:snowflake];
    [self.view.layer insertSublayer:snowEmitter atIndex:0];
}
@end
